package com.cdc.servlet.fileupload;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/FilesUploadServlet")
@MultipartConfig(location = "E://upload", maxFileSize = -1, maxRequestSize = -1, fileSizeThreshold = 1)
public class MultiFileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = -5424963607388841835L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//遍历所有的part部件
		for (Part part : request.getParts()) {
		    //如果表单文件名不为空，才执行下列操作
		    if(!part.getSubmittedFileName().equals("")){
		        String disposition = part.getHeader("content-disposition");
		        System.out.println(disposition);
		     // 获取上传的文件名
				String nameS = part.getSubmittedFileName();
		        System.out.println("文件名称：" + nameS);
				String pathS = request.getSession().getServletContext().getRealPath("/") + "upload\\";
				System.out.println("文件路径：" + pathS);
		        //截取到文件名的后缀
		        String suffix = nameS.substring(nameS.lastIndexOf("."));
		        System.out.println("文件后缀：" + suffix);
		        //随机生成一个UUID
		        String uuid = UUID.randomUUID().toString();
		        //保存到pathS目录下
		        part.write(pathS + nameS+"_"+uuid + suffix);
		        request.setAttribute("msg", disposition+pathS + nameS+"_"+uuid + suffix);
		    }
		}
		request.getRequestDispatcher("servlet/uploadfile/uploadFiles.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
